package com.bite.messageQueue;

import com.bite.messageQueue.common.*;
import com.bite.messageQueue.mqServer.VirtualHost;
import com.bite.messageQueue.mqServer.core.BasicProperties;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消息队列的本体服务器
 * 本质是一个TCP服务器
 */
@Slf4j
public class BrokerServer {
    private ServerSocket serverSocket = null;
    //当前系统默认有一个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");
    //用来保存所有会话，保存当前连接的客户端
    //key是channelId，value为对应的socket对象
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    //用处理多个服务器的请求
    private ExecutorService executorService = null;
    //引入一个Boolean变量控制服务器的启动与关闭
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        log.info("BrokerServer启动！！！");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                Socket clientSocket = serverSocket.accept();
                // 把处理连接的逻辑丢给这个线程池.
                executorService.submit(() -> {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException | ClassNotFoundException | MqException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器停止运行!");
            e.printStackTrace();
        }
    }

    public void stop() throws IOException {
        runnable = false;
        executorService.shutdownNow();
        serverSocket.close();
    }

    private void processConnection(Socket accept) throws IOException, ClassNotFoundException, MqException {
        try (InputStream in = accept.getInputStream();
             OutputStream out = accept.getOutputStream()) {
            log.info("客户端连接成功，客户端信息为：{}", accept);
            //按特定格式处理连接
            try (DataInputStream dataInputStream = new DataInputStream(in);
                 DataOutputStream dataOutputStream = new DataOutputStream(out)) {
                while (true) {
                    //读取客户端发送的请求
                    Request request = readRequest(dataInputStream);
                    //响应请求
                    Response response = process(request, accept);
                    //将响应发送给客户端
                    writeResponse(dataOutputStream, response);
                }
            }
        } catch (EOFException | SocketException e) {
            log.info("客户端断开连接，客户端信息为：{}", accept);
            //客户端断开连接，清理资源
            accept.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                accept.close();
                //清理被关闭会话的所有channel
                clearClosedSession(accept);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void clearClosedSession(Socket accept) {
        // 这里要做的事情, 主要就是遍历上述 sessions hash 表, 把该被关闭的 socket 对应的键值对, 统统删掉.
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == accept) {
                // 不能在这里直接删除!!!
                // 这属于使用集合类的一个大忌!!! 一边遍历, 一边删除!!!
                // sessions.remove(entry.getKey());
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelId) {
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理 session 完成! 被清理的 channelId=" + toDeleteChannelId);
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("读取数据不完整");
        }
        request.setPayload(payload);
        return request;
    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        dataOutputStream.flush();
    }

    private Response process(Request request, Socket accept) throws IOException, ClassNotFoundException, MqException {
        //1、初步解析request的payload
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        log.info("[Request] rid=" + basicArguments.getRid() + ", channelId=" + basicArguments.getChannelId());
        log.info("收到客户端请求，请求类型为：{}", request.getType());

        boolean ok = true;
        //2、根据请求类型，调用不同的方法处理
        if (request.getType() == 0x1) {
            //创建channel
            sessions.put(basicArguments.getChannelId(), accept);
            System.out.println("创建sessions:" + sessions + "channelId = " + basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            //销毁channel
            sessions.remove(basicArguments.getChannelId());
            System.out.println("销毁sessions:" + sessions + "channelId = " + basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            //创建交换机
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getName(), arguments.getExchangeType(),
                    arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
            System.out.println("创建交换机成功！");
        } else if (request.getType() == 0x4) {
            //销毁交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            //创建队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getName(), arguments.isDurable(),
                    arguments.isExclusive(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            //销毁队列
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (request.getType() == 0x7) {
            //创建绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(), arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            //删除绑定
            QueueUnBindArguments arguments = (QueueUnBindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            //发送消息
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(), arguments.getBasicProperties(), arguments.getBody());
        } else if (request.getType() == 0xa) {
            //订阅消息
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoACK(), new Consumer() {
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                    // 先知道当前这个收到的消息, 要发给哪个客户端.
                    // 此处 consumerTag 其实是 channelId. 根据 channelId 去 sessions 中查询, 就可以得到对应的
                    // socket 对象了, 从而可以往里面发送数据了
                    // 1. 根据 channelId 找到 socket 对象
                    Socket clientSocket = sessions.get(consumerTag);
                    if (clientSocket == null || clientSocket.isClosed()) {
                        throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭!");
                    }
                    // 2. 构造响应数据
                    SubScribeReturns subScribeReturns = new SubScribeReturns();
                    subScribeReturns.setChannelId(consumerTag);
                    subScribeReturns.setRid(""); // 由于这里只有响应, 没有请求, 不需要去对应. rid 暂时不需要.
                    subScribeReturns.setOk(true);
                    subScribeReturns.setConsumerTag(consumerTag);
                    subScribeReturns.setBasicProperties(basicProperties);
                    subScribeReturns.setBody(body);
                    byte[] payload = BinaryTool.toBytes(subScribeReturns);
                    Response response = new Response();
                    // 0xc 表示服务器给消费者客户端推送的消息数据.
                    response.setType(0xc);
                    // response 的 payload 就是一个 SubScribeReturns
                    response.setLength(payload.length);
                    response.setPayload(payload);
                    // 3. 把数据写回给客户端.
                    //    注意! 此处的 dataOutputStream 这个对象不能 close !!!
                    //    如果 把 dataOutputStream 关闭, 就会直接把 clientSocket 里的 outputStream 也关了.
                    //    此时就无法继续往 socket 中写入后续数据了.
                    DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                    writeResponse(dataOutputStream, response); //将响应数据写入socket的输出流
                }
            });
        } else if (request.getType() == 0xb) {
            // 调用 basicAck 确认消息.
            BasicACKArguments arguments = (BasicACKArguments) basicArguments;
            ok = virtualHost.basicACK(arguments.getQueueName(), arguments.getMessageId());
        } else {
            // 当前的 type 是非法的.
            throw new MqException("[BrokerServer] 未知的 type! type=" + request.getType());
        }
        // 3. 构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] rid=" + basicReturns.getRid() + ", channelId=" + basicReturns.getChannelId()
                + ", type=" + response.getType() + ", length=" + response.getLength());
        return response;
    }


    /**
     * 获取
     *
     * @return serverSocket
     */
    public ServerSocket getServerSocket() {
        return serverSocket;
    }

    /**
     * 设置
     *
     * @param serverSocket
     */
    public void setServerSocket(ServerSocket serverSocket) {
        this.serverSocket = serverSocket;
    }

    /**
     * 获取
     *
     * @return virtualHost
     */
    public VirtualHost getVirtualHost() {
        return virtualHost;
    }

    /**
     * 设置
     *
     * @param virtualHost
     */
    public void setVirtualHost(VirtualHost virtualHost) {
        this.virtualHost = virtualHost;
    }

    /**
     * 获取
     *
     * @return session
     */
    public ConcurrentHashMap<String, Socket> getSession() {
        return sessions;
    }

    /**
     * 设置
     *
     * @param sessions
     */
    public void setSession(ConcurrentHashMap<String, Socket> sessions) {
        this.sessions = sessions;
    }

    /**
     * 获取
     *
     * @return executorService
     */
    public ExecutorService getExecutorService() {
        return executorService;
    }

    /**
     * 设置
     *
     * @param executorService
     */
    public void setExecutorService(ExecutorService executorService) {
        this.executorService = executorService;
    }

    /**
     * 获取
     *
     * @return runnable
     */
    public boolean isRunnable() {
        return runnable;
    }

    /**
     * 设置
     *
     * @param runnable
     */
    public void setRunnable(boolean runnable) {
        this.runnable = runnable;
    }

    @Override
    public String toString() {
        return "BrokerServer{serverSocket = " + serverSocket + ", virtualHost = " + virtualHost + ", sessions = " + sessions + ", executorService = " + executorService + ", runnable = " + runnable + "}";
    }
}
